package co.za.itweb.itwebpro;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Vector;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

public class SearchActivity extends Activity {
	static JSONObject jsonObject;
	LinearLayout fragmentHolder;
	static boolean refreshed = false;
	static JSONObject sectionsName;
	static List<String> sectionsOrdering;
	static Vector<String> sections=new Vector<String>(0);;
	static JSONObject sectionsNameFromCache;
	static String[] feedtitles = null;
	
	private Dialog dialog;
	Bundle saved;
	static JSONArray sectionsOrder;
	ListView verticallist;
	SearchAdapter verticalAdapter;
	static Vector<JSONSearchHolder> List = new Vector<JSONSearchHolder>(0);
	private InputStream is;
	static JSONArray webOrder;
	public static JSONObject websiteData;
	static Dialog dialog2;
	protected static final String LOGIN_NAME = "LOGIN";
	protected static final String FIRSTRUN = "RUNNED";
	static String orientation;
	static int imagewidth;
	static String density;
	static int unit;
	public static int GalleryWidth;
	String databases[] = { "itweb", "bstorm", "iweek", "cweb" };
	static String database;
	static int index;
	static String searchterm;
	static String cachedir;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		saved = savedInstanceState;
		setContentView(R.layout.activity_main_search);
		Bundle extras = getIntent().getExtras();
		index = extras.getInt("data");
		database = databases[index];
		searchterm = extras.getString("term");
		
		
		checkTextSize();
		if (internetConnection()) {
			
			
			Intent intent = new Intent(SearchActivity.this, Search.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(intent, 1);
			

		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(
					"There is no internet connection.Please connect to the internet and try again.")
					.setCancelable(false)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {

									dialog.cancel();
									finish();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		}
		unit = 100;
		if (isXLargeScreen(getApplicationContext())) {
			unit = 200;
		}

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		if (determineDensity() == "ldpi") {
			imagewidth = (int) (unit * 1.3);
		} else if (determineDensity() == "mdpi") {
			imagewidth = (int) (unit);
		} else if (determineDensity() == "hdpi") {
			imagewidth = (int) (unit) - (unit / 3);
		} else if (determineDensity() == "xdpi") {
			imagewidth = (int) (unit) - (unit / 2);
		}

		
		Button buttonclose = (Button) findViewById(R.id.back);
		buttonclose.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				jsonObject=null;
				sectionsOrdering=null;
				List.clear();
				sections.clear();
				sectionsNameFromCache=null;
				finish();
			}
		});
		GalleryWidth = metrics.widthPixels;

		orientation = getOrientation(getApplicationContext());
	}

	public void updateFeeds() {

		File file = new File(Environment.getExternalStorageDirectory()
				.getPath() + "/ITWebPRO/searchJSON.txt");
		if (file.exists()) {

			try {

				String text = "";
				BufferedReader br = new BufferedReader(new FileReader(file));
				String line;

				while ((line = br.readLine()) != null) {
					text += line;
				}
				br.close();

				JSONObject JO;

				try {
					JO = new JSONObject(text);
					jsonObject = JO;
					sectionsNameFromCache = JO
							.getJSONObject("sections_available");
					sectionsOrder = JO.getJSONArray("sections_order");
					cachedir=JO.getString("url_cache_images");
					sectionsOrdering = JsonUtil2
							.getStringListFromJsonArray(sectionsOrder);
					
					generateJSONHolder(sectionsOrdering);
					if(List.size()==0){
						Toast.makeText(this, "No results found", Toast.LENGTH_SHORT)
						.show();
						finish();
					}
					
					verticallist = (ListView) findViewById(R.id.verticallist);
					sections = new Vector<String>(new LinkedHashSet<String>(sections));
					/*
					for(int u=0;u<List.size();u++){
						for(int n=0;n<List.get(u)._itemlist.size();n++){
							for(int c=0;c<sections.size();c++){
								if(List.get(u)._itemlist.get(n).getCategory()!=sections.get(c)){
									List.remove(u);
								}
							}
						}
					}
					*/
					System.out.println(sections.size()+"SECTIONS SIZE");
					System.out.println(List.size()+"LIST SIZE");
					verticalAdapter = new SearchAdapter(SearchActivity.this, sections);
					verticallist.setAdapter(verticalAdapter);
					verticalAdapter.notifyDataSetChanged();

				} catch (JSONException e) {

					e.printStackTrace();
				}

			} catch (IOException e) {
				System.out.println(e.toString());
			}
			
			File oldfile = new File(Environment.getExternalStorageDirectory()
					.getPath() + "/ITWebPRO/searchJSON.txt");
			oldfile.delete();

		}

	}

	public void generateJSONHolder(List<String> l) {
		String cat="";
		for (int d = 0; d < l.size(); d++) {
			
			
			try {
				if(SearchActivity.jsonObject.has(l.get(d))){
				JSONSearchHolder holder = new JSONSearchHolder();
				JSONArray JA = SearchActivity.jsonObject.getJSONArray(l.get(d));
				if(JA!=null){
				for (int t = 0; t < JA.length(); t++) {
					
					JsonSearchItems jsonlist = new JsonSearchItems();
					JSONObject row = (JSONObject) JA.getJSONObject(t);
					jsonlist.setItemId(row.getString("itemID"));
					jsonlist.setTitle(row.getString("title"));
					jsonlist.setCategory(row.getString("section"));
					cat=row.getString("section");
					
					if (row.has("introImage")) {
						jsonlist.setIntroImage(row.getString("introImage"));
					} else {
						jsonlist.setIntroImage("*");
					}
					if (row.has("introText")) {
						jsonlist.setIntroText(row.getString("introText"));
					} else {
						jsonlist.setIntroText("*");
					}
					holder._itemlist.add(jsonlist);
				}
				if(cat.length()>2){
				sections.add(cat);
				
				}
				List.add(holder);
				}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			

		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1) {

			if (resultCode == 1) {
				writeToCache();
				Toast.makeText(getApplicationContext(), "Search results ",
						Toast.LENGTH_SHORT).show();

				//updateFeeds();

			}

			if (resultCode == 0) {
				Toast.makeText(getApplicationContext(),
						"Sorry no search results found ", Toast.LENGTH_SHORT)
						.show();
				SearchActivity.jsonObject=null;
				finish();

			}

		}

		

	}

	public boolean internetConnection() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();

		return (info != null && info.isConnected());

	}

	public void showNotification() {
		Toast.makeText(getApplicationContext(), "Loading failed...",
				Toast.LENGTH_SHORT).show();
	}

	public void checkTextSize() {
		try {
			SharedPreferences myPrefs = getSharedPreferences(
					SearchActivity.LOGIN_NAME, MODE_WORLD_READABLE);
			String prefName = myPrefs.getString(
					"co.za.itweb.itwebpro.textsize", "login");
			prefName = prefName.replaceAll("/", "");

			JSONArray dat;
			dat = new JSONArray(prefName);

			for (int t = 0; t < dat.length(); t++) {
				try {
					String obj = dat.getJSONObject(t).getString("text");

					if (obj.length() > 0) {
						News.discrete = Integer.parseInt(obj);
					}

				} catch (JSONException e) {
					e.printStackTrace();

				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();

		}

	}

	public String determineDensity() {
		switch (getResources().getDisplayMetrics().densityDpi) {
		case DisplayMetrics.DENSITY_LOW:
			density = "ldpi";

			break;
		case DisplayMetrics.DENSITY_MEDIUM:
			density = "mdpi";

			break;
		case DisplayMetrics.DENSITY_HIGH:
			density = "hdpi";

			break;
		case DisplayMetrics.DENSITY_XHIGH:
			density = "xdpi";

			break;
		}
		return density;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			if (dialog != null && dialog.isShowing()) {
				updateFeeds();
				dialog.dismiss();
			} else {
				jsonObject=null;
				sectionsOrdering=null;
				List.clear();
				sections.clear();
				sectionsNameFromCache=null;
				finish();
			}

		}
		return super.onKeyDown(keyCode, event);
	}

	public static boolean isXLargeScreen(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
	}

	@SuppressWarnings("deprecation")
	public String getOrientation(Context context) {

		final int rotation = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay().getOrientation();
		switch (rotation) {
		case Surface.ROTATION_0:
			return "portrait";
		case Surface.ROTATION_90:
			return "landscape";
		case Surface.ROTATION_180:
			return "portrait";
		default:
			return "landscape";
		}
	}
	
	
	public void writeToCache() {
		
			File storagePath = new File(Environment
					.getExternalStorageDirectory().getPath() + "/ITWebPRO");
			storagePath.mkdirs();
			
			File gpxfile = new File(storagePath + "/searchJSON.txt");
			FileWriter writer;
			try {
				if (jsonObject != null) {
					writer = new FileWriter(gpxfile);
					String result = jsonObject.toString();
					writer.append(result);
					writer.flush();
					writer.close();
					updateFeeds();// /////////////////////////updating feeds
									// after
					                // writing cache
				}

			} catch (IOException e) {

				e.printStackTrace();
			
			}
		
	}

}
